package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private VMService vmService;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 创建工单，运营运维共用
     *
     * @param model
     */
    @Override
    public boolean createTask(TaskViewModel model) {

        VmVO vmInfo = vmService.getVMInfo(model.getInnerCode());
        //校验售货机状态
        checkVm(vmInfo, model.getProductType());

        if (hasTask(vmInfo.getInnerCode(), model.getProductType())) {
            throw new LogicException("该机器有未完成的工单");
        }

        TaskEntity task = new TaskEntity();

        task.setTaskCode(generateTaskCode());

        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        task.setCreateType(model.getCreateType());
        task.setInnerCode(model.getInnerCode());
        task.setAssignorId(model.getAssignorId());
        task.setUserId(model.getUserId());
        UserVO user = userService.getUser(model.getUserId());
        if (user == null) {
            throw new LogicException("执行人不存在");
        }
        task.setUserName(user.getUserName());

        task.setDesc(model.getDesc());
        task.setProductTypeId(model.getProductType());

        task.setAddr(vmInfo.getNodeAddr());
        task.setRegionId(vmInfo.getRegionId());
        save(task);
        //如果是补货工单，向工单明细表插入记录
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {

            List<TaskDetailsViewModel> details = model.getDetails();
            List<Object> list = details.stream().map(new Function<TaskDetailsViewModel, Object>() {
                @Override
                public Object apply(@Nullable TaskDetailsViewModel model) {
                    TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                    BeanUtils.copyProperties(model, detailsEntity);
                    detailsEntity.setTaskId(task.getTaskId());
                    taskDetailsService.save(detailsEntity);
                    return detailsEntity;
                }
            }).collect(Collectors.toList());
        }
        return true;
    }

    /**
     * 取消工单
     *
     * @param taskId
     * @param cancelVm
     * @return
     */
    @Override
    public boolean cancelTask(String taskId, CancelTaskViewModel cancelVm, Integer userId) {
        //判断工单执行人是否为当前登录用户
        Long id = Long.valueOf(taskId);
        TaskEntity task = this.getById(id);
        if (task.getUserId().intValue() != userId.intValue()) {
            throw new LogicException("执行人错误");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单已经完成");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经取消");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVm.getDesc());
        this.updateById(task);
        return true;
    }

    /**
     * 接受工单
     *
     * @param taskId
     * @param userId
     * @return
     */
    @Override
    public boolean acceptTask(String taskId, Integer userId) {
        //判断工单执行人是否为当前登录用户
        Long id = Long.valueOf(taskId);
        TaskEntity task = this.getById(id);
        if (task.getUserId().intValue() != userId.intValue()) {
            throw new LogicException("执行人错误");
        }
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        this.updateById(task);
        return true;
    }

    /**
     * 完成工单
     *
     * @param taskId
     * @param userId
     * @return
     */
    @Override
    public boolean completeTask(String taskId, Integer userId) {
        //判断工单执行人是否为当前登录用户
        Long id = Long.valueOf(taskId);
        TaskEntity task = this.getById(id);
        if (task.getUserId().intValue() != userId.intValue()) {
            throw new LogicException("执行人错误");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单已经完成");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经取消");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(task);
        //运维工单,向emq发送消息更新售货机状态
        if (task.getProductTypeId().equals(VMSystem.TASK_TYPE_DEPLOY)||task.getProductTypeId().equals(VMSystem.TASK_STATUS_CANCEL)) {
            TaskCompleteContract contract = new TaskCompleteContract();
            contract.setInnerCode(task.getInnerCode());
            contract.setTaskType(task.getProductTypeId());
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, JsonUtil.serialize(contract));
            } catch (JsonProcessingException e) {
                log.error("消息发送异常", e);
            }
        }
        //补货工单,向emq发送消息更新售货机库存
        if (task.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            List<TaskDetailsEntity> details = taskDetailsService.getByTaskId(id);
            List<SupplyChannel> list = details.stream().map(new Function<TaskDetailsEntity, SupplyChannel>() {
                @Override
                public SupplyChannel apply(@Nullable TaskDetailsEntity taskDetail) {
                    SupplyChannel supplyChannel = new SupplyChannel();
                    supplyChannel.setChannelId(taskDetail.getChannelCode());
                    supplyChannel.setCapacity(taskDetail.getExpectCapacity());
                    supplyChannel.setSkuId(taskDetail.getSkuId());
                    supplyChannel.setSkuName(taskDetail.getSkuName());
                    supplyChannel.setSkuImage(taskDetail.getSkuImage());
                    return supplyChannel;
                }
            }).collect(Collectors.toList());
            SupplyContract contract = new SupplyContract();
            contract.setSupplyData(list);
            contract.setInnerCode(task.getInnerCode());
            try {
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, JsonUtil.serialize(contract));
            } catch (JsonProcessingException e) {
                log.error("消息发送异常", e);
            }

        }

        return true;

    }

    /**
     * 从redis中找出当日工单最少的运维人员
     *
     * @param vmInfo
     * @return
     */
    @Override
    public Integer getRepairId(VmVO vmInfo) {
        String date = LocalDate.now().plusDays(1).toString();
        String key = "workCount" + date + vmInfo.getRegionId() + VMSystem.USER_REPAIRER;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);
        Object userId = range.stream().collect(Collectors.toList()).get(0);

        return (Integer) userId;
    }

    /**
     * 从redis中找出当日工单最少的运营人员
     *
     * @param vmInfo
     * @return
     */
    @Override
    public Integer getSupplyId(VmVO vmInfo) {
        String date = LocalDate.now().plusDays(1).toString();
        String key = "workCount" + date + vmInfo.getRegionId() + VMSystem.USER_OPERATOR;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);
        Object userId = range.stream().collect(Collectors.toList()).get(0);

        return (Integer) userId;
    }

    /**
     * 校验售货机状态与工单是否匹配
     *
     * @param vmInfo
     * @param productType
     */
    private void checkVm(VmVO vmInfo, int productType) {

        if (vmInfo == null) {
            throw new LogicException("未查询到设备");
        }
        //投放工单
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备在运营中");
        }
        //补货工单
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营中");
        }
        //撤机工单
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营中");
        }
    }

    /**
     * 校验当前售货机是否有未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        LambdaQueryWrapper<TaskEntity> lqw = new LambdaQueryWrapper<>();
        lqw.select(TaskEntity::getTaskId);
        lqw.eq(TaskEntity::getInnerCode, innerCode);
        lqw.eq(TaskEntity::getProductTypeId, productionType);
        lqw.le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(lqw) > 0;
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code." + date;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }
}
